import 'dart:async';

import 'package:flutter/material.dart';
import 'package:shopping_group/event/event.dart';
import 'package:shopping_group/modle/main/ui/lz_preview_image_page.dart';
import 'package:shopping_group/modle/notice/bloc/forum_list_bloc.dart';
import 'package:shopping_group/modle/notice/entity/qry_noticeslst_entity.dart';
import 'package:shopping_group/modle/notice/entity/show_notices_filel.dart';
import 'package:shopping_group/res/colors.dart';
import 'package:shopping_group/res/dimens.dart';
import 'package:shopping_group/utils/object_util.dart';
import 'package:shopping_group/utils/route_util.dart';
import 'package:shopping_group/utils/widget_utils.dart';
import 'package:flutter_staggered_animations/flutter_staggered_animations.dart';
import 'forum_details_page.dart';
import 'forum_release_page.dart';
import 'package:bot_toast/bot_toast.dart';

class ForumPage extends StatefulWidget {
  ForumPage({Key key}) : super(key: key);

  @override
  _ForumPageState createState() => _ForumPageState();
}

class _ForumPageState extends State<ForumPage>
    with AutomaticKeepAliveClientMixin {
  List<QryNoticesLstEntity> _listEntity = [];
  //listview的控制器
  ScrollController _scrollController = ScrollController();
  ForumListBloc _bloc;
  StreamSubscription _refreshSubscription;
  StreamSubscription _loginSubscription;
  DateTime lastPopTime;
  @override
  void initState() {
    super.initState();
    _bloc = ForumListBloc();
    _bloc.initDate.add(null);
    _initListener();
    _refreshSubscription = eventBus.on<RefreshForumEvent>().listen((event) {
      _bloc.initDate.add(null);
    });
    _loginSubscription = eventBus.on<BlackForumEvent>().listen((event) {
      _bloc.initDate.add(null);
    });
  }

  _initListener() {
    _scrollController.addListener(() {
      if (_scrollController.position.pixels ==
          _scrollController.position.maxScrollExtent) {
        _bloc.moreDate.add(_scrollController);
      }
    });
  }

  @override
  Widget build(BuildContext context) {
    return GestureDetector(
      onTap: (() {
        FocusScope.of(context).requestFocus(FocusNode());
      }),
      child: Scaffold(
        resizeToAvoidBottomInset: false,
        body: Container(
          height: double.infinity,
          decoration: BoxDecoration(
            color: Colours.title_white,
          ),
          child: Column(
            children: <Widget>[
              SizedBox(
                height: 32,
              ),
              Row(
                mainAxisAlignment: MainAxisAlignment.spaceBetween,
                children: [
                  Padding(
                    padding: EdgeInsets.only(left: 8),
                    child: WidgetUtils.getTextColorView(
                        '注意：请下拉刷新', Colours.themeColor, Dimens.FONT_SIZE_14,
                        fontweight: FontWeight.w400),
                  ),
                  Container(
                    alignment: Alignment.centerRight,
                    margin: EdgeInsets.only(right: 16),
                    child: GestureDetector(
                      onTap: () {
                        RouteUtil.goParameter(ForumReleasePage());
                      },
                      child: WidgetUtils.showBoxBotton('发布',
                          borderColor: Colours.themeColor,
                          boxColor: Colours.themeColor,
                          textColor: Colours.title_white,
                          horizontalPadding: 16,
                          borderRadius: 20),
                    ),
                  ),
                ],
              ),
              SizedBox(
                height: 8,
              ),
              Expanded(child: _showlistView()),
            ],
          ),
        ),
      ),
    );
  }

  Widget _showlistView() {
    return StreamBuilder(
      stream: _bloc.sendData,
      initialData: _listEntity,
      builder: (BuildContext contexts, AsyncSnapshot<Object> snapshot) {
        Object object = snapshot.data;
        if (object is List) {
          _listEntity = object;
        }
        if (!ObjectUtil.isEmptyList(_listEntity)) {
          _listEntity.forEach((element) {
            element.isSelect = ('Y' == element.currentUserLike);
          });
        }

        int count = _listEntity.length;
        if (0 != count) {
          return Container(
            decoration: new BoxDecoration(
              color: Colors.transparent,
            ),
            child: AnimationLimiter(
              child: RefreshIndicator(
                onRefresh: _pullToRefresh,
                child: ListView.builder(
                  controller: _scrollController,
                  shrinkWrap: true,
                  padding: const EdgeInsets.only(top: 4),
                  itemCount: _listEntity.length,
                  itemBuilder: buildItem,
                ),
              ),
            ),
          );
        } else {
          return Container(
            alignment: Alignment.center,
            child: WidgetUtils.emptyView(
              contexts,
            ),
          );
        }
      },
    );
  }

  //下拉刷新,必须异步async不然会报错
  Future _pullToRefresh() async {
    _listEntity.clear();
    _bloc.initDate.add(null);
    return null;
  }

  //ListView的Item
  Widget buildItem(BuildContext context, int index) {
    return GestureDetector(
      onTap: () {
        RouteUtil.goParameter(ForumDetailsPage(id: _listEntity[index].id));
      },
      child: Container(
        color: Colours.transparent,
        // margin: const EdgeInsets.symmetric(horizontal: 16, vertical: 8),
        child: _xunchaItem(_listEntity[index]),
      ),
    );
  }

  Widget _xunchaItem(QryNoticesLstEntity entity) {
    List<String> imageUrls = getPhotoList(entity.lstNoticesFile);

    return Container(
        padding: const EdgeInsets.symmetric(vertical: 8, horizontal: 8),
        // decoration: BoxDecoration(
        //     border: Border.all(color: Colours.themeColor, width: 1.0),
        //     borderRadius: BorderRadius.circular(15),
        //     color: Colours.title_white),
        child: Column(
          mainAxisAlignment: MainAxisAlignment.start,
          children: <Widget>[
            WidgetUtils.drawCodeDivider(height: 16),
            SizedBox(
              height: 8,
            ),
            Row(
              mainAxisAlignment: MainAxisAlignment.center,
              crossAxisAlignment: CrossAxisAlignment.center,
              children: <Widget>[
                Expanded(
                  child: Row(
                    children: <Widget>[
                      ObjectUtil.isEmptyString(entity.createUserHeadImg)
                          ? Icon(
                              Icons.account_circle,
                              size: 64,
                              color: Colours.themeColor,
                            )
                          : WidgetUtils.clipRRectNetWorkImage(
                              entity.createUserHeadImg,
                              width: 64,
                              height: 64),
                      SizedBox(
                        width: 16,
                      ),
                      Expanded(
                          child: Container(
                              alignment: Alignment.centerLeft,
                              child: Column(
                                mainAxisAlignment: MainAxisAlignment.start,
                                crossAxisAlignment: CrossAxisAlignment.start,
                                children: <Widget>[
                                  WidgetUtils.getTextColorView(
                                      entity.createUserNickname,
                                      Colours.text_2222,
                                      Dimens.FONT_SIZE_16,
                                      fontweight: FontWeight.w400),
                                  SizedBox(
                                    height: 4,
                                  ),
                                  WidgetUtils.getTextColorView(
                                      entity.beforeNowTimeLong,
                                      Colours.text_2222,
                                      Dimens.FONT_SIZE_16,
                                      fontweight: FontWeight.w400),
                                ],
                              ))),
                    ],
                  ),
                ),
                GestureDetector(
                  onTap: () {
                    if (null != lastPopTime &&
                        DateTime.now().difference(lastPopTime) <=
                            Duration(milliseconds: 500)) {
                      lastPopTime = DateTime.now();
                      BotToast.showText(text: '连续点击过快');
                      return;
                    } else {
                      lastPopTime = DateTime.now();
                    }
                    _bloc.dianZanDate.add(entity.id);
                  },
                  child: Container(
                    color: Colours.transparent,
                    child: Icon(
                      Icons.thumb_up,
                      color: entity.isSelect
                          ? Colours.themeColor
                          : Colours.gray_f0,
                      size: 24,
                    ),
                  ),
                ),
                SizedBox(
                  width: 2,
                ),
                WidgetUtils.getTextColorView(
                  entity.fineCt,
                  Colours.text_2222,
                  Dimens.FONT_SIZE_12,
                  textAlign: TextAlign.end,
                ),
              ],
            ),
            SizedBox(
              height: 8,
            ),
            WidgetUtils.drawDivider(),
            SizedBox(
              height: 8,
            ),
            Container(
              alignment: Alignment.bottomLeft,
              child: WidgetUtils.getTextColorView(
                  entity.title, Colours.text_2222, Dimens.FONT_SIZE_16,
                  fontweight: FontWeight.w500),
            ),
            SizedBox(
              height: 8,
            ),
            Container(
              alignment: Alignment.centerLeft,
              child: WidgetUtils.getTextColorView(
                entity.info,
                Colours.text_2222,
                Dimens.FONT_SIZE_14,
              ),
            ),
            SizedBox(
              height: 4,
            ),
            ObjectUtil.isEmptyList(entity.lstNoticesFile)
                ? Container()
                : WidgetUtils.buildGridViewWidget(imageUrls),
            SizedBox(
              height: 4,
            ),
          ],
        ));
  }

  List<String> getPhotoList(List<ShowNoticesFilelEntity> lstFile) {
    List<String> listPhoto = [];
    lstFile.forEach((element) {
      if (null != element &&
          !ObjectUtil.isEmptyString(element.notisFileType) &&
          'NFT_IMG' == element.notisFileType) {
        listPhoto.add(element.fileUrl);
      }
    });
    return listPhoto;
  }

  @override
  void dispose() {
    _refreshSubscription?.cancel();
    _loginSubscription?.cancel();
    super.dispose();
  }

  @override
  bool get wantKeepAlive => true;
}
